<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Services\AuthService;
use App\Services\CommonService;
use App\Services\LogService;
use Auth;
use Illuminate\Support\Facades\DB;
use Request;
use Validator;
use App\Libs\Geetestlib;

class CommonAPIController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', [
            'except' => ['upload', 'startCaptchaServlet', 'verifyLoginServlet'],
        ]);
        $this->commonSvc = new CommonService;
        $this->logSvc = new LogService;
    }

    public function upload()
    {
        $user = Request::user();
        $file = Request::file('file');
        $acceptFileExtensions = ['zip', 'rar', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'jpg', 'jpeg', 'gif', 'png', 'tif', 'bmp'];
        $errorMessage = '不允许上传这个类型的文件';
        if (Request::has('accept_file_type')) {
            $fileType = Request::get('accept_file_type');
            if ($fileType == 'pdf') {
                $acceptFileExtensions = ['pdf'];
                $errorMessage = '只允许上传 PDF 文件';
            }
        }
        if (!in_array($file->extension(), $acceptFileExtensions, true)) {
            $result = ['ok' => false, 'message' => $errorMessage];
            return $this->json($result);
        }
        $fileRecord = $this->commonSvc->storeUploadedFile($file);
        $this->logSvc->sinfo('上传文件', null, $user, null);
        $result = ['ok' => true, 'url' => $fileRecord->path];
        return $this->json($result);
    }

    public function startCaptchaServlet()
    {
        $captchaId = config('vars.captcha_id');
        $privateKey = config('vars.private_key');
        $GtSdk = new GeetestLib($captchaId, $privateKey);
        session_start();
        $data = array(
            "user_id" => "test", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );

        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        return $GtSdk->get_response_str();
    }

    public function verifyLoginServlet()
    {
        error_reporting(0);
        session_start();
        $captchaId = config('vars.captcha_id');
        $privateKey = config('vars.private_key');
        $GtSdk = new GeetestLib($captchaId, $privateKey);
        $data = array(
            "user_id" => $_SESSION['user_id'], # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );


        if ($_SESSION['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
            if ($result) {
                return '{"status":"success"}';
            } else {
                return '{"status":"fail"}';
            }
        } else {  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'])) {
                return '{"status":"success"}';
            } else {
                return '{"status":"fail"}';
            }
        }
    }

    public function getWorkflowPhases() {
        $phases = DB::table('workflow_phases')->get();
        return [
            'ok' => true,
            'code' => 0,
            'msg' => 'ok',
            'phases' => $phases,
        ];
    }

}